package com.sailmi.common.secure.user;
import com.sailmi.common.tool.utils.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationTargetException;


public class UserProviderFactory {
	private final UserProviderProperties userProviderProperties;
	private static final Logger log = LoggerFactory.getLogger(UserProviderFactory.class);

	public UserProviderFactory(){
		userProviderProperties = SpringUtil.getBean("userProviderProperties");
	}
	/**
	 * 自动获取用户代理
	 * 需要在nacos中配置ucs.userprovider.providerName
	 * @return
	 */
	@Bean(name = "userProvider")
    IUserProvider getUserProvider(){
		if(null==userProviderProperties){
			log.info(this.getClass().getName()+": 未初始化用户系统提供者配置【ucs.userprovider.providerName】！");
			return null;
		}
		String userProviderName=userProviderProperties.providerName;

		String userDriver=null;
		if(null!=userProviderProperties.getProviderDriver()){//如果配置了driver
			userDriver = userProviderProperties.getProviderDriver();
		}else{//如果没有配置driver ，则采用约定
			userDriver="com.sailmi.plugin.userprovider."+userProviderName;
			userDriver = userDriver+".UserProvider";
		}
		try {
			log.info(this.getClass().getName()+": ADD User Provider AS "+userDriver+" Successed!");
			IUserProvider userClient= (IUserProvider) Class.forName(userDriver).getDeclaredConstructor().newInstance();
			return userClient;
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(e);
		}
		log.info(this.getClass().getName()+": ADD User Provider AS "+userDriver+" Failed!");
		return null;
	}

}
